/*
 * DocumentWrapperFilter.java
 *
 * Created on September 30, 2005, 3:24 PM
 *
 * (C) R. Alexander Milowski alex@milowski.com
 */

package org.infoset.xml.filter;

import java.net.URI;
import org.infoset.xml.*;
import org.infoset.xml.Item.ItemType;

/**
 *
 * @author R. Alexander Milowski
 */
public class DocumentWrapperFilter implements ItemFilter
{
   
   int sentLevel;
   ItemDestination output;
   ItemConstructor currentConstructor;
   /** Creates a new instance of DocumentWrapperFilter */
   public DocumentWrapperFilter()
   {
      sentLevel = -1;
   }
   
   public DocumentWrapperFilter(ItemDestination out) 
   {
      sentLevel = -1;
      output = out;
   }

   public void attach(ItemDestination output) 
      throws XMLException
   {
      this.output = output;
   }

   public void send(Item item) 
      throws XMLException
   {
      if (sentLevel<0 && item.getType()!=ItemType.DocumentItem) {
         currentConstructor = item.getInfoset().createItemConstructor();
         URI base = item instanceof Parent ? 
            ((Parent)item).getBaseURI() : 
            null;
         output.send(currentConstructor.createDocument(base));
      }
      switch (item.getType()) {
         case DocumentItem:
            sentLevel++;
            break;
         case ElementItem:
            sentLevel++;
            if (sentLevel==0) {
               // TODO: this shouldn't be need in streaming.  All elements should have localized declarations.
               //((Element)item).localizeNamespaceDeclarations();
            }
            break;
         case ElementEndItem:
         case DocumentEndItem:
            sentLevel--;
      }
      output.send(item);
      if (sentLevel<0 && item.getType()!=ItemType.DocumentEndItem) {
         output.send(currentConstructor.createDocumentEnd());
      }   
   }
   
}
